package com.liyunc.demo.util;


import com.liyunc.demo.validate.ImageCode;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Random;

/**
 * 验证码生成工具类.
 */
public class ValidateCodeUtil {

    public static final String SESSION_KEY_IMAGE_CODE = "SESSION_KEY_IMAGE_CODE";
    public static final int EXPIRE_TIME = 60;

    //随机产生只有数字的字符串
    private static final char[] RAND_STRING = {
        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
        'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
        'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
        'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
        'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};


    /**
     * 生成随机验证码及图片.
     * Object[0]：验证码字符串；
     * Object[1]：验证码图片。
     */
    public static ImageCode createImage() {
        //定义图片相关
        final int width = 95;//图片宽度
        final int height = 40;//图片高度
        final int lineSize = 10;//干扰线数量
        final int stringNum = 4;//随机产生字符数量
        final int fontSize = 25;//字体大小

        StringBuilder sb = new StringBuilder();
        //1.创建空白图片
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        //2.获取图片画笔
        Graphics graphics = image.getGraphics();
        //3.设置画笔颜色
        graphics.setColor(Color.LIGHT_GRAY);
        //4.绘制矩形背景
        graphics.fillRect(0, 0, width, height);
        //5.画随机数字
        Random random = new Random();
        for (int i = 0; i < stringNum; i++) {
            //取随机字符索引
            int index = random.nextInt(RAND_STRING.length);
            //设置随机颜色
            graphics.setColor(getRandomColor());
            //设置字体大小
            graphics.setFont(new Font(null, Font.BOLD + Font.ITALIC, fontSize));
            //画字符
            graphics.drawString(RAND_STRING[index] + "", i * width / stringNum, height * 2 / 3);
            //记录字符
            sb.append(RAND_STRING[index]);
        }
        //6.画干扰线
        for (int j = 0; j < lineSize; j++) {
            //设置随机颜色
            graphics.setColor(getRandomColor());
            //画随机线
            graphics.drawLine(random.nextInt(width), random.nextInt(height), random.nextInt(width),
                random.nextInt(height));
        }
        return new ImageCode(image, sb.toString(), EXPIRE_TIME);
    }

    /**
     * 获取随机颜色.
     */
    public static Color getRandomColor() {
        final int number = 256;
        Random random = new Random();
        return new Color(random.nextInt(number), random.nextInt(number), random.nextInt(number));
    }

}
